package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.constant.CartConstant;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;
    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public List<CartItem> getUserCartItem() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        // 判断是否登录
        if(userInfoTo.getUserId()==null){
            return null;
        }else{
            // 已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartList = getCartList(cartKey);
            List<CartItem> collect = cartList.stream().filter((item) -> {
                // 过滤选中的商品
                return item.getCheck();
            }).map((item) -> {
                // 商品的价格需要实时查询
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> opts = getCartOpts();
        opts.delete(skuId.toString());
    }

    // 修改商品的数量
    @Override
    public void countItem(Long skuId, Integer num) {
        // 获取商品
        CartItem cartItem = getCartItem(skuId);
        // 修改商品数量
        cartItem.setCount(num);
        // 转为JSON字符串
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> opts = getCartOpts();
        opts.put(skuId.toString(),s);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        // 获取单个商品
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck((check==1)?true:false);
        BoundHashOperations<String, Object, Object> opts = getCartOpts();
        // redis中要保存json数据
        String s = JSON.toJSONString(cartItem);
        opts.put(skuId.toString(),s);
    }

    // 购物车列表展示逻辑：首先判断是否登录，没有登录则展示临时购物车，
    // 若登录则展示合并后的购物车，将临时购物车合并后并清空
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempUserKey = CART_PREFIX + userInfoTo.getUserKey();
        // 3.未登录,展示临时购物车
        List<CartItem> linshicartList = getCartList(tempUserKey);
        // 1.判断是否登录
        if(userInfoTo.getUserId()!=null){
                // 2.登录
                String userKey = CART_PREFIX + userInfoTo.getUserId();
                List<CartItem> cartList = getCartList(tempUserKey);
                if(cartList!=null && linshicartList.size()>0){
                    for (CartItem cartItem : cartList) {
                        // 合并临时购物车,存在则叠加,不存在则新增
                        addToCart(cartItem.getSkuId(),cartItem.getCount());
                    }
                }
                // 合并完删除临时购物车
                deleteCart(tempUserKey);
                // 查询合并完之后的购物车
                List<CartItem> itemList = getCartList(userKey);
                cart.setCartItems(itemList);
        }else{
            cart.setCartItems(linshicartList);
        }
        return cart;
    }

    // 编写获取购物车的方法
    private List<CartItem> getCartList(String tempUserKey){
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(tempUserKey);
        // 获取所有商品数据
        List<Object> values = ops.values();
        if(values!=null && values.size()>0){
            List<CartItem> items = values.stream().map((obj) -> {
                String item = (String) obj;
                CartItem cartItem = JSON.parseObject(item, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return items;
        }
        return null;
    }

    // 删除临时购物车
    public void deleteCart(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        String item = (String) cartOpts.get(skuId.toString());

        // redis中无此商品,需要往购物车中添加新商品
        if (StringUtils.isEmpty(item)) {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 1.远程服务调用获取sku的信息
                R r = productFeignService.info(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setDefaultImg(skuInfo.getSkuDefaultImg());
                cartItem.setCheck(true);
                cartItem.setCount(num);
            }, executor);

            CompletableFuture<Void> getSaleAttrsAsStringTask = CompletableFuture.runAsync(() -> {
                // 2.获取销售属性
                List<String> saleAttrs = productFeignService.getSaleAttrAsString(skuId);
                cartItem.setSkuAttr(saleAttrs);
            }, executor);

            // 阻塞等待各个任务执行完成
            CompletableFuture.allOf(getSkuInfoTask, getSaleAttrsAsStringTask).get();

            // 3.存储cartItem到Redis中
            // 为了方便Redis序列化将pojo变成json字符串否则会使用jdk的序列化器
            String s = JSON.toJSONString(cartItem);
            cartOpts.put(skuId.toString(), s);
            return cartItem;
        } else {
            // 购物车中有此商品只需要数量的叠加
            CartItem cartItem = JSON.parseObject(item, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String s = JSON.toJSONString(cartItem);
            cartOpts.put(skuId.toString(), s);
            return cartItem;
        }
    }

    // 获取购物车中的商品
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> opts = getCartOpts();
        String item = (String)opts.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(item, CartItem.class);
        return cartItem;
    }

    private BoundHashOperations<String, Object, Object> getCartOpts(){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        // 判断是否登录
        if(userInfoTo.getUserId()!=null){
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else{
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> boundHashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return boundHashOperations;
    }
}
